<template>
  <div class="member-bg">
    <div class="member-card" @scroll="handleScroll">
      <div class="member-search-row" >
        <div class="sw">
          <button :class="['switch-btn', activeTab === 'pingce' ? 'active' : '']" @click="activeTab = 'pingce'">{{ $t('views.report.assessmentReport') }}</button>
          <button :class="['switch-btn', activeTab === 'xunlian' ? 'active' : '']" @click="activeTab = 'xunlian'">{{ $t('views.report.trainingReport') }}</button>
        </div>
        <input v-model="search" class="member-search" :placeholder="$t('views.report.searchPlaceholder')" />
        <button style="margin-left: -45px;" class="member-search-btn" @click="doSearch">
          <i class="iconfont icon-sousuo" style="font-size: 25px;"></i>
        </button>
      </div>

      <div style="height: 66vh; overflow-y: auto;">
        <table class="member-table">
        <thead>
          <tr>
            <th style="width: 190px;">{{ $t('views.report.name') }}</th>
            <th style="width: 220px;">{{ $t('views.report.reportTime') }}</th>
            <th style="width: 180px;">{{ $t('views.report.reportCategory') }}</th>
            <th style="width: 320px;">{{ $t('views.report.reportName') }}</th>
            <th style="width: 400px;"></th>
     
          </tr>
        </thead>
        <tbody class="table-body">
          <tr v-if="users.length === 0" class="no-data">
            <td colspan="4">
              <div class="no-data-content">
                <i class="iconfont icon-wushuju" style="font-size: 48px; color: #ddd;"></i>
                <div style="margin-top: 12px;">{{ $t('views.report.noRecords') }}</div>
              </div>
            </td>
          </tr>
          <tr  v-else v-for="(user, idx) in users" :key="user.id" @click="selectUser(user.id)" :class="{selected: selectedId === user.id}" style="cursor:pointer;">

            <td>{{ user.patientName }}</td>
            <td>{{ user.createTime }}</td>
            <td>{{ user.gameTypeName || $t('views.report.assessmentScale') }}</td>
            <td>{{ user.scaleName||user.gameName }}</td>

            <td class="u-f" style="justify-content: flex-end;"> 
              <button class="member-btn" v-if="activeTab=='pingce'" @click.stop="showTui(user)">{{ $t('views.report.recommendTraining') }}</button>
              <button class="member-btn" @click.stop="goDetail(user)">{{ $t('views.report.details') }}</button>
              <button class="member-btn danger" @click.stop="deleteUser(user)">{{ $t('views.report.delete') }}</button>
            </td>
          </tr>
        </tbody>
      </table>
      </div>
      <div class="page">
        <button class="page-btn u-f-ajc" @click="goPrevPage" :disabled="pageNum <= 1">
          <i class="iconfont icon-zuobian"></i>
        </button>
        
        <template v-for="page in getPageNumbers()" :key="page">
          <button 
            v-if="page !== '...'"
            class="page-number u-f-ajc" 
            :class="{ active: page === pageNum }"
            @click="goToPage(page)"
          >
            {{ page }}
          </button>
          <span v-else class="page-ellipsis">...</span>
        </template>
        
        <button class="page-btn u-f-ajc" @click="goNextPage" :disabled="pageNum >= totalPage">
          <i class="iconfont icon-youbian"></i>
        </button>
      </div>
      <!-- <button class="member-add-btn" @click="addUser">添加用户</button> -->
    </div>


    <Dialog ref="deleteDialogRef">
      <div class="switch-dialog-content">
        <div class="switch-dialog-title">{{ $t('views.report.confirmDelete') }}</div>
        <div class="dialog-btn" style="margin-top: 30px;">
          <button class="dialog-confirm" @click="onDeleteConfirm">{{ $t('common.confirm') }}</button>
          <button class="dialog-cancel" @click="deleteDialogRef.close()">{{ $t('common.cancel') }}</button>
        </div>
      </div>
    </Dialog>
    <Dialog ref="tuiDialogRef">
      <div class="tui-dialog-content">
        <div class="tui-dialog-title" style="font-weight: bold;">{{ $t('views.report.recommendTraining') }}</div>
        <div class="tuie">
          <div class="tui-grid">
            <div class="tui-item" @click="goGame(item)" v-for="item in tuiList" :key="item.title">
              <img :src="BaseUrl+item.cover" class="tui-icon" />
              <div class="tui-title">{{ item.name }}</div>
            </div>
          </div>
        </div>
        <div style="color: #999;font-size: 14px;margin-top: 10px;">
          {{ $t('views.report.trainingDescription') }}
        </div>
      </div>
    </Dialog>
    <SetConfig ref="setConfigRef" />

  </div>
</template>

<script setup lang="ts">
import { ElLoading } from 'element-plus'
import { onActivated, onMounted, onUnmounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import Dialog from '../../components/Dialog.vue'
import { BaseUrl, request } from '../../utils/request'
import SetConfig from '../home/components/SetConfig.vue'

// 定义组件名称，用于 keep-alive
defineOptions({
  name: 'report'
});

// 使用备用翻译系统
let t: any = (key: any) => key
let setLang = (newLang: any) => {}

// 创建响应式的翻译函数
const translationVersion = ref(0)
const $t = (key: any, params?: any) => {
  // 依赖translationVersion来触发响应式更新
  translationVersion.value
  if (params) {
    return t(key, params)
  } else {
    return t(key)
  }
}

// 初始化翻译函数
const initTranslations = async () => {
  try {
    const fallback = await import('../../utils/i18n-fallback')
    t = fallback.t
    setLang = (newLang: any) => {
      fallback.setLang(newLang)
      translationVersion.value++
    }
    // 监听语言变化事件
    window.addEventListener('language-changed', () => {
      translationVersion.value++
    })
    // 强制更新一次以确保翻译生效
    translationVersion.value++
    console.log('Translation system initialized for report page')
  } catch (error) {
    console.warn('Failed to load i18n fallback:', error)
  }
}
const route = useRoute()

interface User {
  id: string
  name: string
  gender: string
  birthday: string
  remark: string
}
const setConfigRef = ref<any>(null)

const router = useRouter()
const search:any = ref('')
const selectedId = ref('')
// 从localStorage读取上次的tab状态，如果没有则默认为评估报告
const activeTab = ref(localStorage.getItem('reportActiveTab') || 'pingce')
const tuiDialogRef = ref()
const pageNum = ref(1)
const pageSize = ref(8)
const loading = ref(false)
const hasMore = ref(true)
let requestId = 0

const users = ref<any[]>([])
const goGame = (item: any) => {
  if (item.config) {
    setConfigRef.value.show(item)

  } else { 
    router.push({
    path: '/game',
    query: {
      gameId: item.id
    }
  })
  }

}
async function loadData() {
  if (loading.value) return
  
  // 生成新的请求ID
  const currentRequestId = ++requestId
  
  const loadingEl = ElLoading.service({
    lock: false,
    text: $t('common.loading'),
    background: 'rgba(0, 0, 0, 0)',
  })
  loading.value = true
  
  try {
    const url = activeTab.value === 'pingce' ? '/system/scaleRecord/list' : '/system/record/list'
    const res = await request(url, {
      method: 'GET',
      params: {
        patientId: patientId.value,
        queryConditions: search.value,
        pageNum: pageNum.value,
        pageSize: pageSize.value
      }
    })
    
    // 只处理最新的请求结果
    if (currentRequestId === requestId) {
      loadingEl.close()
      users.value = res.rows || []
      totalPage.value = Math.max(1, Math.ceil((res.total || 0) / pageSize.value))
      hasMore.value = pageNum.value < totalPage.value
      loading.value = false
    } else {
      // 如果不是最新请求，只关闭loading
      loadingEl.close()
    }
  } catch (error) {
    // 只处理最新的请求错误
    if (currentRequestId === requestId) {
      loadingEl.close()
      loading.value = false
      console.error(error)
    } else {
      loadingEl.close()
    }
  }
}

watch(activeTab, (newTab) => {
  // 保存当前tab状态到localStorage
  localStorage.setItem('reportActiveTab', newTab)
  
  pageNum.value = 1
  hasMore.value = true
  loadData()
})

function handleScroll(e: any) {
  const { scrollHeight, scrollTop, clientHeight } = e.target
  if (scrollHeight - scrollTop - clientHeight < 50) {
    pageNum.value++
    loadData()
  }
}
const patientId:any = ref('')
onMounted(async () => {
  await initTranslations()
  let user: any =JSON.parse(localStorage.getItem('user') || '{}')
  console.log(user);
  
  patientId.value =user.id
  if (route.query.userId) {
    patientId.value = route.query.userId
  } 
  console.log(patientId.value);
  
  loadData()
  enableTableBodyTouch()
})
onUnmounted(() => {
  disableTableBodyTouch()
  // 重置请求ID，确保旧请求结果不会被处理
  requestId = 0
})

// 当组件被激活时（从 keep-alive 缓存中恢复）
onActivated(() => {
  console.log('Report component activated - returning from detail page')
  
  // 重新启用触摸事件（防止事件监听器丢失）
  enableTableBodyTouch()
  
  // 确保activeTab状态正确恢复
  const savedTab = localStorage.getItem('reportActiveTab')
  if (savedTab && savedTab !== activeTab.value) {
    console.log('Restoring activeTab from localStorage:', savedTab)
    activeTab.value = savedTab
  }
  
  console.log('Current page state preserved:', {
    activeTab: activeTab.value,
    pageNum: pageNum.value,
    search: search.value,
    selectedId: selectedId.value,
    usersCount: users.value.length
  })
  
  // 如果需要刷新数据，取消注释下面这行
  // loadData()
})

function enableTableBodyTouch() {
  const el = document.querySelector('.member-table tbody') as HTMLElement
  if (!el) return
  let isTouching = false
  let startY = 0
  let scrollTop = 0
  // 触摸
  el.addEventListener('touchstart', function (e) {
    const te = e as TouchEvent
    if (te.touches.length !== 1) return
    isTouching = true
    startY = te.touches[0].pageY - el.offsetTop
    scrollTop = el.scrollTop
  }, { passive: true })
  el.addEventListener('touchmove', function (e) {
    if (!isTouching) return
    const te = e as TouchEvent
    if (te.touches.length !== 1) return
    const y = te.touches[0].pageY - el.offsetTop
    const walkY = y - startY
    el.scrollTop = scrollTop - walkY
    te.preventDefault()
  }, { passive: false })
  el.addEventListener('touchend', function () {
    isTouching = false
  })
  // 鼠标拖动
  let isDown = false
  let mouseStartY = 0
  let mouseScrollTop = 0
  el.addEventListener('mousedown', (e: MouseEvent) => {
    isDown = true
    mouseStartY = e.pageY - el.offsetTop
    mouseScrollTop = el.scrollTop
    el.classList.add('dragging')
  })
  el.addEventListener('mouseleave', () => {
    isDown = false
    el.classList.remove('dragging')
  })
  el.addEventListener('mouseup', () => {
    isDown = false
    el.classList.remove('dragging')
  })
  el.addEventListener('mousemove', (e: MouseEvent) => {
    if (!isDown) return
    e.preventDefault()
    const y = e.pageY - el.offsetTop
    const walkY = y - mouseStartY
    el.scrollTop = mouseScrollTop - walkY
  })
}
function disableTableBodyTouch() {
  // 如需移除事件可在此实现
}

const showTui = (user: any) => {
  if (!user.scaleId) return
  request(`/system/game/getRecommend/${user.scaleId}`, { method: 'GET' }).then(res => {
    console.log(res);
    if (res.length) {
      tuiList.value = res || []
      tuiDialogRef.value.open()
    } else { 
      window.messageRef?.show($t('views.report.noRecommendedTraining'), 'error')
    }
 
  })
}

function selectUser(id: string) {
  selectedId.value = id
}
const addType = ref(0)
function doSearch() {
  pageNum.value = 1
  hasMore.value = true
  loadData()
}
function editUser(user: any) {
  addType.value = 1
  dialogRef.value.open()
}
const switchDialogRef = ref()
const switchUserName = ref('')
let switchUserObj: any = null
function switchUser(user: any) {
  switchUserName.value = user.name
  switchUserObj = user
  switchDialogRef.value.open()
}
const deleteDialogRef = ref()
const deleteUserName = ref('')
let deleteUserObj: any = null
function deleteUser(user: any) {
  deleteUserName.value = user.name
  deleteUserObj = user
  deleteDialogRef.value.open()
}

function goDetail(user: any) {
  if(activeTab.value === 'pingce'){
  router.push({
    path: '/table',
    query: {
      id: user.id
    }
  })
  }else{
    router.push({
      path: '/tableGame',
      query: {
        id: user.id
      }
    })
  }
}
const form = ref({
  name: '',
  birthday: '',
  gender: '男',
  id: '',
  remark: ''
})
const dialogRef = ref()
function onFormConfirm() {
  // 校验和保存逻辑
  dialogRef.value.close()
}
function onSwitchConfirm() {
  // 这里写切换用户的实际逻辑，比如selectedId.value = switchUserObj.id
  selectedId.value = switchUserObj.id
  switchDialogRef.value.close()
}
function onDeleteConfirm() {
  // 实际删除逻辑
  users.value = users.value.filter(u => u.id !== deleteUserObj.id)
  deleteDialogRef.value.close()
  window.request?.('/system/scaleRecord/'+deleteUserObj.id, { method: 'DELETE' }).then(res => {
    console.log(res);
    loadData()
  })
}
const tuiList = ref<any[]>([])

const totalPage = ref(1)
function getPageNumbers() {
  const pageNumbers = []
  let start = Math.max(pageNum.value - 2, 1)
  let end = Math.min(pageNum.value + 2, totalPage.value)

  if (start > 1) {
    pageNumbers.push(1)
    if (start > 2) {
      pageNumbers.push('...')
    }
  }
  for (let i = start; i <= end; i++) {
    pageNumbers.push(i)
  }
  if (end < totalPage.value) {
    if (end < totalPage.value - 1) {
      pageNumbers.push('...')
    }
    pageNumbers.push(totalPage.value)
  }
  return pageNumbers
}
function goPrevPage() {
  if (pageNum.value > 1) {
    pageNum.value--
    loadData()
  }
}
function goNextPage() {
  if (pageNum.value < totalPage.value) {
    pageNum.value++
    loadData()
  }
}
function goToPage(page: number | string) {
  if (typeof page === 'number') {
    pageNum.value = page
    loadData()
  }
}
</script>

<style scoped>
.table{
  height: 100px;
}
.member-bg {
  width: 100vw;
  height: 100vh;
  background: transparent;
  display: flex;
  align-items: center;
  justify-content: center;
}
.member-card {
  width: 90vw;
  max-width:90vw;
  height: 80vh;
  background: #fff;
  border-radius: 18px;
  box-shadow: 0 8px 32px rgba(30,94,146,0.10), 0 2px 8px rgba(0,0,0,0.10);
  padding: 32px 32px 32px 32px;
  position: relative;
  margin-top: -60px;
}
.member-search-row {
  display: flex;
  align-items: center;
  margin-bottom: 18px;
  border-radius: 20px;


}
.member-search {
  background: #dddddd;

  flex: 1;
  height: 55px;
  border-radius: 25px;
  font-size: 18px;
	border: none;
  padding: 0 16px;
  outline: none;
}
.member-search-btn {
  width: 55px;
  height:  55px;
  margin-left: 10px;
  border: none;
  background: var(--theme-primary);
  color: #fff;
  border-radius: 50%;
  font-size: 20px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}
.member-table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0 12px;
  background: transparent;
  font-size: 17px;
}
.member-table th {
  color: #888;
  font-weight: 500;
  background: none;
  padding-bottom: 8px;
  text-align: left;
  padding-left: 20px;
}
.member-table td {
  background: #f6fafd;
  text-align: left;
  padding: 10px 20px;
  color: #333;
}
.member-table tr {
  transition: background 0.2s;
}
.member-btn {
  background: var(--theme-primary);
  color: #fff;
  border: none;
  border-radius: 18px;
  padding: 7px 18px;
  /* width: 100px; */
  margin: 0 4px;
  font-size: 15px;
  cursor: pointer;
  transition: background 0.2s;
}
.member-btn.danger {
  background: #e14c4c;
}
.member-btn:active {
  background: var(--theme-primary-hover);
}
.member-add-btn {
  position: absolute;
  right: 32px;
  bottom: 24px;
  background: var(--theme-primary);
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 8px 32px;
  font-size: 18px;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(30,94,146,0.10);
}
.member-add-btn:active {
  background: var(--theme-primary-hover);
}
.user-form-dialog {
  min-width: 800px;
  margin-top: 20px;
  padding: 20px 10px 10px 10px;
}
.form-row {
  display: flex;
  align-items: center;
  margin-bottom: 18px;
  gap: 18px;
}
.form-label {
  min-width: 70px;
  color: #333;
  font-size: 17px;
}
.form-input {
  width: 280px;
  height: 36px;
  margin-left: 10px;
  border: 1px solid #d0d0d0;
  border-radius: 6px;
  padding: 0 10px;
  font-size: 16px;
  margin-right: 18px;
}
.form-radio {
  margin-right: 10px;
  font-size: 16px;
  color: #333;
}
.form-textarea {
  width: 100%;
  min-height: 60px;
  border: 1px solid #d0d0d0;
  border-radius: 6px;
  font-size: 16px;
  padding: 8px 10px;
  resize: none;
  margin-bottom: 0;
}
.dialog-btn {
  display: flex;
  justify-content: center;
  gap: 24px;
  margin-top: 32px;
}
.dialog-confirm {
  min-width: 90px;
  background: var(--theme-primary);
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 18px;
  padding: 8px 0;
  cursor: pointer;
  transition: background 0.2s;
}
.dialog-confirm:hover {
  background: var(--theme-primary-hover);
}
.dialog-cancel {
  min-width: 90px;
  background: #f3f3f3;
  color: #888;
  border: none;
  border-radius: 8px;
  font-size: 18px;
  padding: 8px 0;
  cursor: pointer;
  transition: background 0.2s;
}
.dialog-cancel:hover {
  background: #e0e0e0;
}
.switch-dialog-content {
  min-width: 380px;
  padding: 30px 30px 10px 30px;
  text-align: center;
}
.switch-dialog-title {
  font-size: 22px;
  color: #222;
  margin-bottom: 10px;
  font-weight: 500;
}
.member-table tr.selected td {
  background: var(--theme-secondary) !important;
  color: #fff !important;
}
.sw {
  display: flex;
  align-items: center;
  margin-right: 30px;
  background-color: #ddd;
  border-radius: 50px;
}
.switch-btn {
  min-width: 140px;
  height: 55px;
  border: none;
  outline: none;
  font-size: 20px;
  font-weight: 500;
  border-radius: 30px;
  background-color: #ddd;

  cursor: pointer;
}
.switch-btn.active {
  background: var(--theme-primary);
  color: #fff;
}
.tui-dialog-content {
  min-width: 800px;
  padding: 30px 30px 10px 30px;
  text-align: center;
}
.tui-dialog-title {
  font-size: 22px;
  color: #222;
  margin-bottom: 10px;
  font-weight: 500;
}
.tui-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 32px 36px;
  justify-items: center;
  margin: 30px 0 10px 0;
}
.tui-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 110px;
  height: 110px;
}
.tui-icon {
  width: 64px;
  height: 64px;
  border-radius: 16px;
  background: #f5fafd;
  margin-bottom: 8px;
  border: 1px solid #ddd;
  object-fit: cover;
}
.tui-title {
  color: #222;
  font-size: 16px;
  text-align: center;
  margin-top: 2px;
}
.no-data {
  text-align: center;
}
.no-data td {
  background: #fff !important;
  padding: 60px 0 !important;
}
.no-data-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #999;
  font-size: 16px;
}
.page {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
}
.page-btn {
  width: 40px;
  height: 40px;
  border: none;
  background: #f3f3f3;
  color: #888;
  font-size: 18px;
  cursor: pointer;
  border-radius: 50%;
  margin: 0 4px;
}
.page-number {
  width: 40px;
  height: 40px;
  border: none;
  background: #f3f3f3;
  color: #888;
  font-size: 18px;
  cursor: pointer;
  border-radius: 50%;
  margin: 0 4px;
}
.page-number.active {
  background: var(--theme-primary);
  color: #fff;
}
.page-ellipsis {
  margin: 0 8px;
  color: #888;
  font-size: 18px;
}
.member-table tbody.dragging {
  cursor: grabbing;
  user-select: none;
}
</style>